package org.jwd.core.web;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * @author vizz
 * @since 2022/5/17 13:59
 * 请求对象
 */
public class Req {
    /**
     * 从请求中获取IP地址
     */
    public static String getClientIpAddress(HttpServletRequest request) {
        String clientIp = request.getHeader("X-Forwarded-For");

        if (StringUtils.isNotEmpty(clientIp) && !StrUtil.equalsIgnoreCase("unKnown", clientIp)) {
            int index = clientIp.indexOf(",");
            if (index != -1) {
                return clientIp.substring(0, index);
            } else {
                return clientIp;
            }
        }

        clientIp = request.getHeader("X-Real-IP");
        if (StringUtils.isNotEmpty(clientIp) && !StrUtil.equalsIgnoreCase("unKnown", clientIp)) {
            return clientIp;
        }

        return request.getRemoteAddr();
    }
}
